package com.common.serialize.impl;

import com.common.exception.SerializeException;
import com.common.serialize.CommonSerializer;
import com.common.serialize.SerializerCode;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author Zixiang Hu
 * @description 使用jdk自带的序列化机制
 * @create 2021-02-27-19:52
 */
@Slf4j
public class JDKSerializer implements CommonSerializer {
    @Override
    public byte[] serialize(Object obj) {
        byte[] bytes = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
        } catch (Exception e) {
            log.error("JDKSerializer的serialize发送异常");
            throw new SerializeException("JDKSerializer的serialize发送异常");
        }
        return bytes;
    }

    @Override
    public Object deserialize(byte[] bytes, Class<?> clazz) {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            Object o = ois.readObject();
            return o;
        } catch (Exception e) {
            log.error("JDKSerializer的serialize发送异常");
            throw new SerializeException("JDKSerializer的serialize发送异常");
        }
    }

    @Override
    public int getCode() {
        return SerializerCode.valueOf("JDK").getCode();
    }
}
